﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace ReservoirManger
{
    public partial class Captcha : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //调用生成验证码的方法，并把生成的验证码临时存储在Session中
            this.GenImg(this.GenCode(4));
            Session["image"] = this.GenCode(4);
            Server.Transfer("Login.aspx");
        }
        //随机产生的验证码字符数量
        private string GenCode(int num)
        {
            string[] source = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P,", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" };
            string code = "";
            //创建Random类的实例
            Random rd = new Random();
            //获取验证码
            for (int i = 0; i < num; i++)
            {
                code += source[rd.Next(0, source.Length)];
            }
            //返回产生的验证码
            return code;
        }

        //生成图片
        private void GenImg(string code)
        {
            //创建Random类的实例
            Random r = new Random();
            //定义一个画板
            Bitmap myPalette = new Bitmap(120, 40);
            //在画板上定义绘图的实例
            Graphics gh = Graphics.FromImage(myPalette);
            //定义一个矩形 (给验证码框设置宽和高)
            Rectangle rc = new Rectangle(0, 0, myPalette.Width, myPalette.Height);
            //填充矩形 (给验证码框设置背景颜色)
            gh.FillRectangle(new SolidBrush(Color.Khaki), rc);
            //设置各种字体以及每个字体单独的颜色
            for (int i = 0; i < code.Length; i++)
            {
                //随机生成颜色
                Color color = Color.FromArgb(r.Next(0, 255), r.Next(0, 255), r.Next(0, 255));
                //设置颜色
                SolidBrush s = new SolidBrush(color);
                //设置每个字的坐标
                PointF f = new PointF(i * 25 + 10, r.Next(1, 10));
                //绘制字符在图片上面
                gh.DrawString(code[i].ToString(), new Font("微软圆滑", 16), s, f);
            }
            for (int i = 0; i < 4; i++)
            {
                //随机生成颜色
                Color color = Color.FromArgb(r.Next(0, 255), r.Next(0, 255), r.Next(0, 255));
                //绘制一条线
                gh.DrawLine(new Pen(color, 1), new Point(r.Next(0, 100), r.Next(0, 30)), new Point(r.Next(0, 100), r.Next(0, 30)));
            }
            //设置验证码图片的格式
            myPalette.Save(Response.OutputStream, ImageFormat.Jpeg);
            //释放图片资源
            gh.Dispose();
            myPalette.Dispose();
        }
    }
}